<template>
  <a-spin :spinning="loading">
    <j-form-container>
      <a-form-model ref="form" :model="ruleForm" :rules="rules" slot="detail" :loading="loading">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="编号" prop="houseNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="ruleForm.houseNo" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="门牌号" prop="houseNumber" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="ruleForm.houseNumber" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="户数" prop="householdNum" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="ruleForm.householdNum" placeholder="请输入" type="number"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="常住人口数"
              prop="permanentPopulation"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-model="ruleForm.permanentPopulation" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="房屋总建筑面积（平方米）"
              prop="buildingArea"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-model="ruleForm.buildingArea" placeholder="请输入" type="number"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="房屋总占地面积（平方米）"
              prop="housingArea"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-model="ruleForm.housingArea" placeholder="请输入" type="number"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="建成时间" prop="buildDate" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker showTime valueFormat="YYYY-MM-DD HH:mm:ss" v-model="ruleForm.buildDate" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" />
          <a-col :span="24">
            <a-form-model-item label="房屋地址" prop="position" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div class="flex-contain">
                <a-input v-model="ruleForm.position" placeholder="请输入"></a-input>
                <a-button type="link" @click="setPosition">定位</a-button>
              </div>
            </a-form-model-item>
            <a-form-model-item label="经纬度" prop="lng" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="ruleForm.lng" placeholder="请输入"></a-input>
            </a-form-model-item>
            <div style="width: 100%; height: 200px">
              <Map ref="map" @getCenter="setCenter" />
            </div>
          </a-col>

          <!-- 问题信息 -->
          <a-col :span="24">
            <span>存在问题信息</span>
            <a-button type="link" @click="ruleForm.quesList.push(JSON.parse(JSON.stringify(question_init)))"
              >+新增问题</a-button
            >
          </a-col>
          <a-col :span="24" v-for="(item, index) in ruleForm.quesList || []" :key="index">
            <div class="flex-contain flex-justify-content-space-between">
              <div class="flex-contain flex-column width100">
                <div class="flex-contain flex-justify-content-space-between font-bold marBottom10">
                  <span>问题 {{ index - -1 }}</span>
                  <span class="cursor">删除问题</span>
                </div>
                <div class="flex-contain">
                  <div class="flex-contain flex-column width100">
                    <div>
                      <a-form-model-item label="问题类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <a-select
                          v-model="item.quesType"
                          :getPopupContainer="node => node.parentNode"
                          style="width: 100%;"
                        >
                          <a-select-option v-for="(type, i) in questionTypeList" :key="index + i" :value="type.value">{{
                            type.name
                          }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </div>
                    <div class="flex-contain flex-wrap item-list">
                      <div v-for="(pic, p_index) in item.picDataList" :key="index + p_index" class="item pic-box">
                        <div class="opa-area flex-contain flex-column flex-justify-content-center">
                          <div class="flex-contain" style="margin: auto">
                            <a-icon
                              type="delete"
                              @click="deletePic(item.picDataList, p_index)"
                              class="font-size-30 font-icon-white"
                            />
                          </div>
                        </div>
                        <a-avatar shape="square" :src="pic.url" class="pic" />
                      </div>
                      <a-upload
                        style="width: unset; margin: auto 0"
                        v-model="item.picDataList"
                        accept="jpg,jpeg,bmp,png"
                        name="pic"
                        listType="picture-card"
                        multiple
                        :file-list="item.picDataList"
                        :showUploadList="false"
                        @change="val => handleChangeUpload(index, val)"
                      >
                        <a-icon type="plus" class="font-size-40" />
                      </a-upload>
                      <!-- 测试 -->
                      <!--                      item.picDataList: {{ item.picDataList }}-->
                      <!--                      <j-image-upload name='pic' :is-multiple='false' upload-action='/common/upload/pic' class="avatar-uploader" text=' ' v-model="item.picDataList" ></j-image-upload>
                      <div v-for='(pic, p_index) in item.picDataList'>
                        <j-image-upload name='pic' :is-multiple='true' upload-action='/common/upload/pic' class="avatar-uploader" text=' ' v-model="pic" ></j-image-upload>
                      </div>-->
                    </div>
                  </div>
                  <div class="width100">
                    <a-form-model-item label="问题描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-textarea type="textarea" v-model="item.quesDesc" :rows="6" />
                    </a-form-model-item>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getDictList, getDictItemList, commonUploadPic } from '@/api/system'
import Map from '@/views/components/Town/map.vue'
import axios from 'axios'
import { houseAdd, houseEdit } from '../../../api/House'

const DEFAULT_RULEFORM = {
  houseNo: '',
  houseNumber: '',
  householdNum: '',
  permanentPopulation: '',
  buildingArea: '',
  housingArea: '',
  buildDate: '',
  position: '',
  lng: '',
  longitude: '',
  latitude: '',
  quesList: []
}

export default {
  components: {
    Map
  },
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      ruleForm: JSON.parse(JSON.stringify(DEFAULT_RULEFORM)),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      loading: false,
      rules: {},
      question_init: {
        quesType: '',
        quesDesc: '',
        picDataList: []
      },
      questionTypeList: []
    }
  },
  watch: {
    data: {
      handler(v) {
        if ((v || {}).id) {
          const ruleForm = JSON.parse(JSON.stringify(v))
          // 格式化附件信息
          ruleForm.quesList = (ruleForm.quesList || []).map(x => {
            let picDataList = []
            try {
              picDataList = JSON.parse(x.picDataList)
            } catch (e) {}
            if (!picDataList || (Array.isArray(picDataList) && (picDataList || []).length === 0)) {
              try {
                picDataList = JSON.parse(x.picData)
              } catch (e) {
                picDataList = []
              }
            }
            return {
              ...x,
              picDataList: (picDataList || []).map(picData => {
                return {
                  ...picData,
                  url: picData.picUrl,
                  name: picData.picName
                }
              })
            }
          })
          this.ruleForm = {
            ...ruleForm,
            houseNo: ruleForm.data.houseNo,
            permanentPopulation: ruleForm.data.permanentPopulation,
            position: ruleForm.data.address,
            lng: ruleForm.data.longitude + ',' + ruleForm.data.latitude,
            longitude: ruleForm.data.longitude,
            latitude: ruleForm.data.latitude
          }
        } else {
          this.ruleForm = JSON.parse(JSON.stringify(DEFAULT_RULEFORM))
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    await this.getDictListFun()
  },
  methods: {
    async getDictListFun() {
      // 获取问题类型枚举
      const params = {
        dictCode: 'ps_house_question_type',
        pageNo: 1,
        pageSize: 1
      }
      await getDictList(params).then(async res => {
        const dictId = (res.result.records || [])[0].id
        if (dictId) {
          const params = {
            dictId
          }
          await getDictItemList(params).then(res => {
            this.questionTypeList = (res.result.records || []).map(x => {
              return {
                name: x.itemText,
                value: x.itemValue
              }
            })
          })
        }
      })
    },
    async uploadPic(outerResolve) {
      let flag = true
      const promise = Promise.all(
        (this.ruleForm.quesList || []).map(async question => {
          if ((question.picDataList || []).length > 0) {
            await question.picDataList.map(async (picData, index) => {
              // 单张单张图片进行上传

              // 已经上传成功的不再重新上传
              if (picData.uid) {
                await new Promise(async (resolve, reject) => {
                  const formData = new window.FormData()
                  formData.append('pic', picData.file, picData.name)
                  await commonUploadPic(formData)
                    .then(res => {
                      // 改写对象内容属性
                      const result = res.result
                      question.picDataList[index] = {
                        url: result.picUrl,
                        name: result.picName,
                        picName: result.picName,
                        picUrl: result.picUrl
                      }
                      resolve()
                    })
                    .catch(e => {
                      flag = false
                      reject()
                    })
                })
              } else {
                picData.picUrl = picData.url
                picData.picName = picData.name
              }
            })
          }
        })
      )

      await promise.then(res => {
        setTimeout(() => {
          if (outerResolve) {
            outerResolve()
          }
          console.log('promise.all')
        }, 1000)
      })
      return flag
    },
    async submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true

          const promise = new Promise(async (resolve, reject) => {
            // 先上传图片
            const flag = await this.uploadPic(resolve)
          })

          promise.then(async () => {
            const params = {
              ...this.ruleForm
            }

            // 测试
            // console.log(params, 'params')
            // return

            let api = null
            if (params.id) {
              api = houseEdit
            } else {
              api = houseAdd
            }
            if (!api) {
              return
            }
            await api(params).then(res => {
              this.loading = false
              this.$emit('ok')
            })
          })
        }
      })
    },
    handleChangeUpload(i, opt) {
      const file = opt.file

      const item = {
        file: file.originFileObj,
        name: file.nane,
        uid: file.uid,
        url: URL.createObjectURL(file.originFileObj)
      }

      if (!this.ruleForm.quesList[i].picDataList.find(x => x.uid === item.uid)) {
        try {
          this.ruleForm.quesList[i].picDataList.push(item)
        } catch (e) {
          this.ruleForm.quesList[i].picDataList = []
          this.ruleForm.quesList[i].picDataList.push(item)
        }
      }
    },
    setCenter(data) {
      try {
        const pos = (data || []).join(',')
        this.$set(this.ruleForm, 'longitude', pos[0])
        this.$set(this.ruleForm, 'latitude', pos[1])
      } catch (e) {}
    },
    setPosition() {
      // 根据小程序端新增时传入的经纬度，定位地图
      const ref = this.$refs.map
      if (ref) {
        // const pos = (this.ruleForm.position || '').split(',')
        const pos = [this.ruleForm.longitude, this.ruleForm.latitude]
        if (Array.isArray(pos) && (pos || []).length === 2) {
          ref.setPosition(pos)
        }
      }
    },
    deletePic(arr, index) {
      arr.splice(index, 1)
    }
  }
}
</script>
<style lang="less" scoped>
.pic-box {
  position: relative;
  .pic {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
.item-list {
  .item {
    width: 33%;
  }
  /* 正方形 */
  .item {
    width: 33%;
    padding-bottom: 33%;
    margin-right: 0.5%;
    margin-bottom: 10px;
  }
  .item:nth-child(3n) {
    margin-right: 0;
  }
}
.opa-area {
  position: absolute;
  z-index: 99;
  width: 100%;
  height: 100%;
  opacity: 0;
}
.opa-area:hover {
  opacity: 1;
  background: rgba(0, 0, 0, 0.5);
}
</style>
